package main

import (
	"gitee.com/yyzh999/webdev/handler"
	"gitee.com/yyzh999/webdev/middleware"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"os"
)

func InitRouter() *gin.Engine {

	// 禁用控制台颜色，将日志写入文件时不需要控制台颜色。
	//gin.DisableConsoleColor()
	gin.ForceConsoleColor()
	f, _ := os.Create("gin.log")
	//将日志同时输出到文件和控制台
	gin.DefaultWriter = io.MultiWriter(f, os.Stdout)

	gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
		log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)
	}

	//router := gin.New()
	router := gin.Default()
	InitTemplate(router)

	json := router.Group("/json")
	{
		json.GET("/AsciiJSON", handler.AsciiJSON)
		json.GET("/JSONP", handler.JSONP)
		json.GET("/NormalJson", handler.NormalJson)
		json.GET("/IndentedJSON", handler.IndentedJSON)
		json.GET("/SecureJSON", handler.SecureJSON)
		json.GET("/PureJSON", handler.PureJSON)
	}

	protocol := router.Group("protocol")
	{
		protocol.GET("/MoreJson", handler.MoreJson)
		protocol.GET("/SomeYaml", handler.SomeYaml)
		protocol.GET("/SomeXML", handler.SomeXML)
		protocol.GET("/Protobuf", handler.Protobuf)

	}

	view := router.Group("view")
	{
		view.GET("/posts/index", handler.PostIndex)
		view.GET("/index", handler.Index)
		view.GET("/users/index", handler.UserIndex)
		view.GET("/raw", handler.Raw)
		view.GET("form", handler.FormHtml)
	}

	bind := router.Group("/bind")
	{
		bind.POST("/login", handler.Longin)
		bind.POST("/form", handler.Form)
		bind.POST("/parameter", handler.QueryAndForm)
		bind.Any("/startPage", handler.StartPage)
		bind.POST("/once", handler.BindBodyOnce)
		bind.POST("/multi", handler.BindBodyMulti)
		bind.POST("/map", handler.BindMap)
		bind.GET("/queryParameter", handler.BindQueryParameter)
		bind.POST("/loginJson", handler.LoginJson)
		bind.POST("/loginXml", handler.LoginXML)
		bind.POST("/loginForm", handler.LoginUseForm)
		bind.POST("/checkbox", handler.BindCheckBox)

		//http://127.0.0.1:9080/bind/uri/zhangsan/987fbc97-4bed-5078-9f07-9141ba07c9f3
		bind.GET("/uri/:name/:id", handler.BindUri)
		bind.GET("/getb", handler.GetDataB)
		bind.GET("/getc", handler.GetDataC)
		bind.GET("getd", handler.GetDataD)
	}

	file := router.Group("/file")
	{
		file.POST("/uploadSingleFile", handler.UploadSingleFile)
		file.POST("/uploadMultiFile", handler.UploadMultiFile)
	}

	reader := router.Group("/reader")
	{
		reader.GET("/someDataFromReader", handler.SomeDataFromReader)
	}

	common := router.Group("/common")
	{
		common.GET("/graceful", handler.GraceFulDown)
		common.GET("/ping", handler.RecordLog)
		common.GET("/bookable", handler.GetBookAble)
		common.GET("/cookie", handler.Cookie)

		common.GET("/user/:name", handler.RouteParameter)
		common.GET("/user/:name/*action", handler.RouteParameterAction)
	}

	/**
	 * gin.BasicAuth 设置身份证认证用户名密码 gin.Accounts 为用户名密码
	 * 默认密码加密方式： 简单的用户名和密码拼接，然后base64
	 *  base := user + ":" + password
	 * return "Basic " + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base))
	 * 客户端调用时 需要在Header 传递Authorization 参数
	 */
	admin := router.Group("/admin", gin.BasicAuth(gin.Accounts{
		"foo":    "bar", //foo 为用户名， bar为密码;
		"austin": "1234",
		"lena":   "hello2",
		"manu":   "4321",
	}))
	{
		admin.GET("/secrets", handler.Secrets)
	}

	// 使用HTTP方法
	//h := router.Group("/h")
	//{
	//	h.GET("/someGet", getting)
	//	h.POST("/somePost", posting)
	//	h.PUT("/somePut", putting)
	//	h.DELETE("/someDelete", deleting)
	//	h.PATCH("/somePatch", patching)
	//	h.HEAD("/someHead", head)
	//	h.OPTIONS("/someOptions", options)
	//}

	mid := router.Group("/mid")
	mid.Use(middleware.AuthRequired)
	{
		mid.GET("/user", handler.UserInfo)
	}

	async := router.Group("/async")
	{
		async.GET("/long_async", handler.LongAsync)
		async.GET("/long_sync", handler.LongSync)
	}

	return router
}

func InitRouter2() *gin.Engine {
	router := gin.Default()
	router.GET("/info", func(context *gin.Context) {
		context.JSONP(http.StatusOK, gin.H{
			"Hello": "xxxxxxxxxxxxxxxxxxdddddd",
		})
	})

	router.GET("/redirect", func(context *gin.Context) {
		context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
	})

	router.POST("/postRedirect", func(context *gin.Context) {
		context.Redirect(http.StatusFound, "/info")
	})

	router.GET("/test", func(context *gin.Context) {
		context.Request.URL.Path = "/test2"
		router.HandleContext(context)
	})

	router.GET("/test2", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{"hello": "world"})
	})

	return router
}
